<?php

$config["dbsetup"][]="xAPProcessPicturesDatabase";


//$config["startup"][]="PicturesScanAll";
$config["timer"][]="PicturesTimer";
//flag to prevent multiple running Timers
$config["PicturesTimerRunning"]=0;


function PicturesTimer(){
	global $config;	
	if (time()>$config["PicturesMinuteTimer"]){
		// set next check for 1 minutes
		$config["PicturesMinuteTimer"]=time()+(60);
		//send xAP Messages
		TimersCheck();
	}
	// check for folders to scan
	if (time()>$config["PicturesTimer"] && $config["PicturesTimerRunning"]==0){
		// set next check for 1 minutes
		$config["PicturesTimer"]=time()+(60);
		//scan folders
		$config["PicturesTimerRunning"]=1;
		PicturesScanAll();
		$config["PicturesTimerRunning"]=0;
		xAPLog("Pictures","Checked","");
	}	
	
	//check folders
	CheckFolders();
}
function CheckFolders(){
	global $config;	
	if (isset($config["monitor"])){
		if (time()>$config["CCTVTimer"]){
			$config["CCTVTimer"]=time(); // max once per second
			foreach($config["monitor"] as $v){
				PicturesCCTVProcess($v);
			}
		}
	}	
}
function TimersCheck(){
	// look at database and find anything that needs triggering
	global $config;	
	$config["monitor"]=array(); // store copy of monitor folder info so as to check folders every second but check DB only every minute
	$now=date("Y-m-d H:i:s");
	$sql="SELECT * FROM xap_pictures_source 
	where nextdatestamp<'".$now."' or nextdatestamp is null";
	$results=dbquery($sql);
	foreach($results as $row){
		//dbexec("update xAP_TV_prog set TriggerEvent='' where ProgID=".$row["ProgID"]); // Done so remove setting
		if($row["SourceType"]==1){
			$config["monitor"][]=$row;
			//just stoore in array for later use in timer routine
		}
	}
	
	
}
	
function PicturesCCTVProcess($row){
	global $config;
	$filetype[]="jpg";
	
	xAPLog("Pictures","Checking ".$row["MonitorLocation"],"");
	//get files
	$files=filelist($row["MonitorLocation"],1);
	
	foreach($files as $f){
		
		xAPLog("Pictures","Processing ".$f,"");
		// make directory structure
		$date=filemtime($f);
		$info=pathinfo($f);
		$nodelete=0;
		if(in_array(strtolower($info["extension"]),$filetype)){
			//make folder to put items in
			$newfolder=$row["Location"]."/".date("Y-m-d/H/i",$date);
			$newfile=$newfolder."/".date("YmdHi",$date)."-".$info["basename"];
			if (!is_dir($newfolder) && strlen($newfolder)>0){
				@mkdir($newfolder,0777,true);
			}
			// copy files
			
			if(copy($f,$newfile)){

				if($config["win"]==1){
					//addslashes
					$newfile=str_replace("/","\\",$newfile);
					$realf=str_replace("\\","\\\\",$newfile);
					//get folder
					$folder=explode("\\\\",$realf);
					unset($folder[(count($folder)-1)]);
					$realfolder=implode("\\\\",$folder);
				}else{
					$realf=$newfile;
					//get folder
					$folder=explode("/",$realf);
					unset($folder[(count($folder)-1)]);
					$realfolder=implode("/",$folder);
				}
				$size = getimagesize($newfile);
				$exif = exif_read_data($newfile);
				
				$sql="insert into xAP_Pictures_Item 
					(Active,FullLocation,FullFolder,SourceID,Width,Height,Orientation,CameraMake,CameraModel,ExposureTime,FNumber,ISOSpeedRatings,DateTaken,CreatedDateStamp) VALUES
					(1,'".dbesc($realf)."',
					'".dbesc($realfolder)."',
					".$row["SourceID"].",
					".$size[0].",
					".$size[1].",
					".intval($exif['IFD0']['Orientation']).",
					'".dbesc($exif['Make'])."',
					'".dbesc($exif['Model'])."',
					'".dbesc($exif['ExposureTime'])."',
					'".dbesc($exif['FNumber'])."',
					'".dbesc($exif['ISOSpeedRatings'])."',
					'".dbesc(date("Y-m-d H:i:s",strtotime($exif['DateTime'])))."',
					'".dbesc(date("Y-m-d H:i:s"))."'
					)";
					dbexec($sql);
					CreateThumbnailImagick($realf,1);
					xAPLog("Image","Picture Inserted ".$newfile,"");
					

					}else{
						$nodelete=1; // flag a failed copy
					}
	}
		if($nodelete==0){
						if(unlink($f)){
						xAPLog("Image","Source Deleted ".$f,"");
						
						}else{
						xAPLog("Image","Source failed to delete ".$f,"");	
						}	
		}
	}
}

function PicturesScanAll(){
	global $config;
	if($config["win"]==1){
			$split="\\";
		}else{
			$split="/";
		}
	
	$now=date("Y-m-d H:i:s");
	$sql="Select Location,SourceID from xAP_Pictures_Source where SourceType=0 and Active=1 and (NextDateStamp<'".$now."' or NextDateStamp is null)";
	$results=dbquery($sql);	
	
	foreach($results as $v){
		//next scan 
			$next=date("Y-m-d H:i:s",strtotime("+6 hours"));
			dbexec("update xAP_Pictures_Source set NextDateStamp='".$next."' where SourceID=".$v["SourceID"]);
		// tag pictures as missing
			dbexec("update xAP_Pictures_Item set Active=0 where SourceID=".$v["SourceID"]);
			
			walkDir($v["Location"],callBackDir,$v["SourceID"]);
			
		//delete anything not found
			dbexec("delete from xAP_Pictures_Item where Active=0 and SourceID=".$v["SourceID"]);
			
	}
}
function PicturesScan($folder,$sourceid){
global $config;
	$filetype[]="jpg";

	$files=filelist($folder);
	//print_r($files);
	foreach($files as $f){
		// fix paths
		
		if($config["win"]==1){
			//addslashes
			$f=str_replace("/","\\",$f);
			$realf=str_replace("\\","\\\\",$f);
			//get folder
			$folder=explode("\\\\",$realf);
			unset($folder[(count($folder)-1)]);
			$realfolder=implode("\\\\",$folder);
		}else{
			$realf=$f;
			//get folder
			$folder=explode("/",$realf);
			unset($folder[(count($folder)-1)]);
			$realfolder=implode("/",$folder);
		}
		
		$sql="select FullLocation from xAP_Pictures_Item where FullLocation='".dbesc($realf)."'";
		$results=dbquery($sql);	

		$info=pathinfo($f);
		if(in_array(strtolower($info["extension"]),$filetype)){
			if($results[0]["FullLocation"]==""){
		echo $sql."\n";
		print_r($results);
				xAPLog("Image","New Picture ".$f,"");

				xAPLog("Image","Picture Get Size ".$f,"");
				$size = getimagesize($f);
				xAPLog("Image","Picture Get EXIF ".$f,"");
				$exif = exif_read_data($f);
				
				$sql="insert into xAP_Pictures_Item 
					(Active,FullLocation,FullFolder,SourceID,Width,Height,Orientation,CameraMake,CameraModel,ExposureTime,FNumber,ISOSpeedRatings,DateTaken,CreatedDateStamp) VALUES
					(1,'".dbesc($realf)."',
					'".dbesc($realfolder)."',
					".$sourceid.",
					".$size[0].",
					".$size[1].",
					".intval($exif['IFD0']['Orientation']).",
					'".dbesc($exif['Make'])."',
					'".dbesc($exif['Model'])."',
					'".dbesc($exif['ExposureTime'])."',
					'".dbesc($exif['FNumber'])."',
					'".dbesc($exif['ISOSpeedRatings'])."',
					'".dbesc(date("Y-m-d H:i:s",strtotime($exif['DateTime'])))."',
					'".dbesc(date("Y-m-d H:i:s"))."'
					)";
					dbexec($sql);
					
					xAPLog("Image","Picture Inserted ".$f,"");
				}else{
					$sql="update xAP_Pictures_Item set
					  Active=1,
					  UpdatedDateStamp='".dbesc(date("Y-m-d H:i:s"))."'
					  where FullLocation='".dbesc($realf)."'";
					dbexec($sql);	
				}
		}
		CreateThumbnailImagick($realf);
		
		//check for CCTV events as these scans can take ages!
		CheckFolders();
		
	}

}
function callbackDir($dir,$sourceid)
{
   # do whatever you want here
   //echo "$dir\n";
   PicturesScan($dir,$sourceid);
}

function walkDir($dir,$fx,$sourceid)
{
  xAPLog("Image","Scanning ".$dir,"");
  $arStack = array();
  $fx($dir,$sourceid);
  if( ($dh=opendir($dir)) )
  { while( ($file=readdir($dh))!==false )
    { if( $file=='.' || $file=='..' ) continue;
      if( is_dir("$dir/$file") )
      { if( !in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
      }
    }
    closedir($dh);
  }
  if( count($arStack) )
  { foreach( $arStack as $subdir )
    { walkDir($subdir,$fx,$sourceid);
    }
  }
}

function filelist( $from = '.',$recursive=0)
{
    if(! is_dir($from))
        return false;
   
    $files = array();
    if( $dh = opendir($from))
    {
        while( false !== ($file = readdir($dh)))
        {
            // Skip '.' and '..'
            if( $file == '.' || $file == '..')
                continue;
            $path = $from . '/' . $file;
            if( is_dir($path) ){
				if($recursive==1){
                $files += filelist($path);
				}
				}else{
                $files[] = $path;
				//echo $path."\n";
				}
        }
        closedir($dh);
    }
    return $files;
}
function CreateThumbnail($picpath,$justthumb=0){
		global $config;
		$picpath=str_replace("\\\\","\\",$picpath);
		$info=pathinfo($picpath);
		$pichash=sha1($picpath);
		$previewhash=sha1($picpath."preview");
		$sendpath=$config["basefolder"]."tmp/Pictures/".substr($pichash,0,4)."/".substr($pichash,4,4)."/".$pichash.".jpg";
		$generate=1;
		// if file is old then recreate
		if(file_exists($cachepath)){
			$generate=0;
			if(filemtime($cachepath)<strtotime("-10 days")){
				$generate=1;
			}
		}
			if($generate==1){
					//settings
					$tile_width=160;
					$tile_height=120;
					$preview_width=640;
					$preview_height=480;
					//thumnail
					$valid=0;
					if(strtolower($info["extension"])=="jpg"){
						xAPLog("Image","Opening Image ".$picpath,"");
						//copy local as it's quicker
						if(copy($picpath,$config["basefolder"]."tmp/Pictures/".$pichash."tmp.jpg")){
							$img = imagecreatefromjpeg( $config["basefolder"]."tmp/Pictures/".$pichash."tmp.jpg" );
							xAPLog("Image","Opening Image Local","");
							}else{
							$img = imagecreatefromjpeg( $picpath );	
							}
						$valid=1;
					}
					
					if($valid==1){

						$width = imagesx( $img );
						$height = imagesy( $img );
						$ratio_orig = $width/$height;
						/*
						if ($width>1000){
							$oldimg=$img;
							$img=imagecreate($preview_width,$preview_width/$ratio_orig);
							fastimagecopyresampled($img,$oldimg,0,0,0,0,$preview_width,$preview_width/$ratio_orig,$width,$height,5);
							$width=$preview_width;
							$height=$preview_width/$ratio_orig;
							imagejpeg( $img, $config["basefolder"]."tmp/Pictures/".$pichash."tmp2.jpg" );
						}
						*/
						//-------------------------------------------------------------------------------------------- thumnail
						// scale correctly
						$new_width=$tile_width;
						$new_height=$tile_height;
						if ($new_width/$new_height > $ratio_orig) {
							$new_width = $new_height*$ratio_orig;
						} else {
							$new_height = $new_width/$ratio_orig;
						}
						//tmp image
						xAPLog("Image","Create Temp Image ".$picpath,"");
						$tmp_img = imagecreatetruecolor( $tile_width, $tile_height );
						$white=imagecolorallocate  ($tmp_img,255,255,255);
						imagefill($tmp_img,0,0,$white);
						xAPLog("Image","Resample Image ".$picpath,"");
						imagecopyresampled    ( $tmp_img, $img, (($tile_width-$new_width)/2), (($tile_height-$new_height)/2), 0, 0, $new_width, $new_height, $width, $height );
						xAPLog("Image","Creating Folder ","");
						@mkdir($config["basefolder"]."tmp/Pictures");
						@mkdir($config["basefolder"]."tmp/Pictures/".substr($pichash,0,4));
						@mkdir($config["basefolder"]."tmp/Pictures/".substr($pichash,0,4)."/".substr($pichash,4,4));
						imagejpeg( $tmp_img, $sendpath );
						// Clean up the memory
						ImageDestroy($tmp_img);
						xAPLog("Image","Created Thumbnail ".$info["basename"],"");
						//-------------------------------------------------------------------------------------------- preview
						if($justthumb==999){
							@mkdir($config["basefolder"]."tmp/Pictures");
							@mkdir($config["basefolder"]."tmp/Pictures/".substr($previewhash,0,4));
							@mkdir($config["basefolder"]."tmp/Pictures/".substr($previewhash,0,4)."/".substr($previewhash,4,4));
							$sendpath=$config["basefolder"]."tmp/Pictures/".substr($previewhash,0,4)."/".substr($previewhash,4,4)."/".$previewhash.".jpg";
							if(file_exists($config["basefolder"]."tmp/Pictures/".$pichash."tmp2.jpg")){
								
								copy($config["basefolder"]."tmp/Pictures/".$pichash."tmp2.jpg",$sendpath);
								
								}else{
							// scale correctly
							$new_width=$preview_width;
							$new_height=$preview_height;
							if ($new_width/$new_height > $ratio_orig) {
								$new_width = $new_height*$ratio_orig;
							} else {
								$new_height = $new_width/$ratio_orig;
							}
							//tmp image
							$tmp_img = imagecreatetruecolor( $preview_width, $preview_height );
							$white=imagecolorallocate  ($tmp_img,255,255,255);
							imagefill($tmp_img,0,0,$white);
							imagecopyresampled    ( $tmp_img, $img, (($preview_width-$new_width)/2), (($preview_height-$new_height)/2), 0, 0, $new_width, $new_height, $width, $height );

							imagejpeg( $tmp_img, $sendpath );
							// Clean up the memory
							ImageDestroy($tmp_img);
						}
							
							xAPLog("Image","Created Preview ".$info["basename"],"");
					}
						
						
						//cleanup
						ImageDestroy($img);
						@unlink($config["basefolder"]."tmp/Pictures/".$pichash."tmp.jpg");
						@unlink($config["basefolder"]."tmp/Pictures/".$pichash."tmp2.jpg");
					}
			}
		
}
function CreateThumbnailImagick($picpath){
	
	$filetype[]="jpg";
	
		global $config;
		$picpath=str_replace("\\\\","\\",$picpath);
		$info=pathinfo($picpath);
		$pichash=sha1($picpath);
		$previewhash=sha1($picpath."preview");
		$sendpath=$config["basefolder"]."tmp/Pictures/Thumbs/".substr($pichash,0,2)."/".substr($pichash,2,2)."/".substr($pichash,4,2)."/".$pichash.".jpg";
		$generate=1;
		// if file is old then recreate
		if(file_exists($sendpath)){
			$generate=0;
			if(filemtime($sendpath)<strtotime("-10 days")){
				$generate=1;
				xAPLog("Image","Existing Thumbnail too old","");
			}
		}
			if($generate==1){
					//settings
					$tile_width=160;
					$tile_height=120;
					$preview_width=640;
					$preview_height=480;
					//thumnail
					$valid=1;

					
					if($valid==1){					
						//-------------------------------------------------------------------------------------------- thumnail

						@mkdir($config["basefolder"]."tmp/Pictures");
						@mkdir($config["basefolder"]."tmp/Pictures/Thumbs");
						@mkdir($config["basefolder"]."tmp/Pictures/Thumbs/".substr($pichash,0,2));
						@mkdir($config["basefolder"]."tmp/Pictures/Thumbs/".substr($pichash,0,2)."/".substr($pichash,2,2));
						@mkdir($config["basefolder"]."tmp/Pictures/Thumbs/".substr($pichash,0,2)."/".substr($pichash,2,2)."/".substr($pichash,4,2));
						
						$cmd=$config["basefolder"]."apache/ImageMagick/convert \"".$picpath."\" -thumbnail \"".$tile_width."x".$tile_height.">\" -gravity center -extent ".$tile_width."x".$tile_height." \"".$sendpath."\"";

						if($config["win"]==1){
							$cmd=str_replace("/","\\",$cmd);
						}
						exec($cmd);
						xAPLog("Image","Created Thumbnail ".$info["basename"],"");
					}
			}
		
}
function xAPProcessPicturesDatabase(){
	dbexec("CREATE TABLE IF NOT EXISTS xAP_Pictures_Source (SourceID INTEGER  AUTO_INCREMENT PRIMARY KEY)");
	dbexec("ALTER TABLE xAP_Pictures_Source add Active INTEGER");
	dbexec("ALTER TABLE xAP_Pictures_Source add Alias VARCHAR(10)");
	dbexec("ALTER TABLE xAP_Pictures_Source add Location VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Source add MonitorLocation VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Source add SourceType INTEGER");//0 Image Store, 1 CCTV
	dbexec("ALTER TABLE xAP_Pictures_Source add LastDateStamp DATETIME");
	dbexec("ALTER TABLE xAP_Pictures_Source add NextDateStamp DATETIME");
	
	
	dbexec("CREATE TABLE IF NOT EXISTS xAP_Pictures_Item (ItemID INTEGER  AUTO_INCREMENT PRIMARY KEY)");
	dbexec("ALTER TABLE xAP_Pictures_Item add Active INTEGER");
	dbexec("ALTER TABLE xAP_Pictures_Item add SourceID INTEGER");
	dbexec("ALTER TABLE xAP_Pictures_Item add Width Integer");
	dbexec("ALTER TABLE xAP_Pictures_Item add Height Integer");
	dbexec("ALTER TABLE xAP_Pictures_Item add Orientation Integer");
	dbexec("ALTER TABLE xAP_Pictures_Item add Comment VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add CameraMake VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add CameraModel VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add ExposureTime VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add FNumber VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add ISOSpeedRatings VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add DateTaken DATETIME");
	dbexec("ALTER TABLE xAP_Pictures_Item add FullLocation VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add FullFolder VARCHAR(255)");
	dbexec("ALTER TABLE xAP_Pictures_Item add CreatedDateStamp DATETIME");
	dbexec("ALTER TABLE xAP_Pictures_Item add UpdatedDateStamp DATETIME");	
	dbexec("ALTER TABLE xAP_Pictures_Item add Thumbnail Integer");
	dbexec("create index FullLocationidx on xAP_Pictures_Item (FullLocation)");
	
	
}
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
  // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
  // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
  // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
  // Author: Tim Eckel - Date: 12/17/04 - Project: FreeRingers.net - Freely distributable.
  //
  // Optional "quality" parameter (defaults is 3).  Fractional values are allowed, for example 1.5.
  // 1 = Up to 600 times faster.  Poor results, just uses imagecopyresized but removes black edges.
  // 2 = Up to 95 times faster.  Images may appear too sharp, some people may prefer it.
  // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled.
  // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
  // 5 = No speedup.  Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled.

  if (empty($src_image) || empty($dst_image)) { return false; }
  if ($quality <= 1) {
    $temp = imagecreatetruecolor ($dst_w + 1, $dst_h + 1);
    imagecopyresized ($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h);
    imagecopyresized ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h);
    imagedestroy ($temp);
  } elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
    $tmp_w = $dst_w * $quality;
    $tmp_h = $dst_h * $quality;
    $temp = imagecreatetruecolor ($tmp_w + 1, $tmp_h + 1);
    imagecopyresized ($temp, $src_image, $dst_x * $quality, $dst_y * $quality, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h);
    imagecopyresampled ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h);
    imagedestroy ($temp);
  } else {
    imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  }
  return true;
}
?>